package com.base.controller;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.helper.RYSmsHelper;
import com.base.po.voip.*;
import com.base.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.base.comm.CommContent;
import com.base.helper.SmsHelper;
import com.base.helper.VosHelper;
import com.base.helper.WebHelper;
import com.base.po.param.VosModelList;
import com.base.po.voip.RechargeablecardsExample.Criteria;
import com.base.utils.GsonUtil;
import com.base.utils.IP;
import com.base.utils.Produce;

/**
 * admin管理系统控制器
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/admin")
public class content_kamianchongzhi {
	@Autowired
	private PayinfoesService payinfoesService;
	@Autowired
	private RechargeablecardsService rechargeablecardsService;
	@Autowired
	private RechargeablecardsGiftService rechargeablecardsGiftService;
	@Autowired
	private SubscribersService subscribersService;
	@Autowired
	private LogsService logsService;// log日志
	@Autowired
	private UsersService usersService;
	@Autowired
	private SmsconfigsService smsconfigsService;
	@Autowired
	private ChangeRecordService changeRecordService;
	@Autowired
	private JpushIdService jpushIdService;

	// 用户首页
	@RequestMapping("/content_kamianchongzhi")
	public ModelAndView index(HttpServletRequest request) throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		// 设置页面进行跳转
		modelAndView.setViewName("jsp/content_kamianchongzhi");
		return modelAndView;
	}

	String SUCCESS = "success";

	/**
	 * 添加充值信息
	 *
	 * 生成充值记录
	 *
	 * 如果为有卡号密码的查询到相关的信息，随后查询其充值金额，并更改充值卡的状态
	 *
	 * @param request
	 * @param response
	 * @param mobile
	 * @param cardno
	 * @param pwd
	 * @param money
	 * @param cardtype
	 * @param type
	 * @throws Exception
	 */
	@RequestMapping(value = "/insertPayinfo", method = RequestMethod.POST)
	public void insertPayinfo(HttpServletRequest request, HttpServletResponse response, String mobile, String cardno,
			String pwd, Integer money, Integer shopMoney, Integer cardtype, Integer type, Integer pushDate)
			throws Exception {
		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		// 验证浏览器缓存
		String usernamesys = (String) request.getSession().getAttribute("useracc");
		String parentid = (String) request.getSession().getAttribute("adminUserId");
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		if (parentid == null || parentid.equals("") || mobile == null || mobile.equals("")) {
			out.print("浏览器丢失了您的信息，请刷新重试");
			return;
		}
		Users curusers = usersService.selectByPrimaryKey(parentid);
		// 用户代理商id
		String parentId = "";
		switch (type) {
		case 1:
			// 1.验证参数是否传递
			if (pwd == null || pwd.equals("") || cardno == null || cardno.equals("")) {
				out.print("参数错误");
				return;
			} else {
				// 2.验证用户是否存在
				SubscribersExample subscribersExample = new SubscribersExample();
				if (adminUsergrade == 0) {
					out.print("ADMIN用户无法为用户充值");
					return;
				} else if (adminUsergrade == 1) {// 当前users就是OEM，查询该users下的用户
					subscribersExample.getOredCriteria().add(subscribersExample.createCriteria()
							.andMobileEqualTo(mobile).andParentidEqualTo(parentid).andDatastatusEqualTo(true));
					parentId = parentid;
				} else if (adminUsergrade == 2) {// 当前users不是OEM是商家，查询该users代理的用户
					subscribersExample.getOredCriteria()
							.add(subscribersExample.createCriteria().andMobileEqualTo(mobile)
									.andParentidEqualTo(curusers.getParentid()).andDatastatusEqualTo(true));
					parentId = curusers.getParentid();
				}
				List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
				if (subscribers.size() > 0) {
					Subscribers users = subscribers.get(0);
					money = 0;
					// 2.验证卡号\卡密是否正确
					if (cardno != null && pwd != null) {
						RechargeablecardsExample example = new RechargeablecardsExample();
						Criteria criteria = example.createCriteria();
						criteria.andCardnoEqualTo(cardno);
						criteria.andPwdEqualTo(pwd);
						criteria.andStatusEqualTo(0);
						example.getOredCriteria().add(criteria);
						List<Rechargeablecards> a = rechargeablecardsService.selectByExample(example);
						if (a != null && a.size() == 1) {
							// 3.验证卡密是否存在,验证卡密是否被使用
							Rechargeablecards cards = a.get(0);
							// 4.验证卡密是否被冻结
							if (cards.getDatastatus()) {
								money = cards.getMoney();
								// 5. 验证该充值卡的代理商是否存在,验证卡密代理商权限（admin不能充值）
								Users cardAgents = usersService.selectByPrimaryKey(cards.getParentid());
								if (cardAgents != null && cardAgents.getDatastatus() == true
										&& cardAgents.getRole() != 0) {
									UsersExample usersExample = new UsersExample();
									usersExample.getOredCriteria().add(usersExample.createCriteria()
											.andDatastatusEqualTo(true).andIdEqualTo(parentid));
									List<Users> agents = usersService.selectByExample(usersExample);
									// 5. 验证该用户的代理商是否存在
									if (agents != null && agents.size() == 1) {
										Users agent = agents.get(0);

										// 查询充值者 变更前话费余额
										BigDecimal beforeB = new BigDecimal(0);
										// 备注
										String remark = null;
										try {
											// TODO 暂时配注
											String userR = VosHelper
													.GetVosAccount("{accounts:['" + agent.getAgentprefix() + users.getMobile() + "']}");
											if (userR != null) {
												VosModelList userR1 = GsonUtil.getObject(userR, VosModelList.class);
												if (userR1.retCode == 0) {
													beforeB = userR1.infoCustomers[0].getMoney();
												} else {
													beforeB = new BigDecimal(0);
													remark = "暂无记录";
												}
											}
										} catch (Exception e) {
											beforeB = new BigDecimal(0);
											remark = "暂无记录";
										}
										//查询充值者  变更前话费有效期
										Date beforeTimeB = users.getEndtime();
										// 查询充值者  变更前购物金余额
										BigDecimal beforeS = BigDecimal.valueOf(users.getShopBalance());
										// 查询充值者 变更前购物金有效期
										Date beforeTimeS = new SimpleDateFormat("yyyy-MM-dd")
												.parse(users.getShopEnddate());
										// 变更话费金额
										BigDecimal changeB = new BigDecimal(0);
										// 变更购物金额
										BigDecimal changeS = new BigDecimal(0);
										// 查询充值者 变更后话费有效期
										Date changeTimeB = new Date();
										// 查询充值者 变更后购物金有效期
										Date changeTimeS = new Date();

										List<String> allShop = usersService.selectAllShop(parentid);
										if(allShop.contains(cards.getParentid()) == false) {
											out.print("充值失败,"+agent.getUsername()+"未找到充值卡信息");
											return ;
										}

										//开卡距离今天几天
										int time = Produce.differentDays(cards.getCreatetime(), Produce.getNowDate());
										//距离时间大于有效期  就是过期了
										if(time>cards.getTermofvalidity()) {
											out.print("充值卡已过期");
											return;
										}

										// 验证卡密类型(判断输入类型是否与卡密类型一致)
										switch (cards.getType()) {
										// a.包月（800）
										case 1:
											cards.setMoney(800);
											users.setIsmonth(true);
											break;
										// b.包季度（2500）
										case 2:
											cards.setMoney(2500);
											users.setIsquarter(true);
											break;
										// c.包年（10000）
										case 3:
											cards.setMoney(10000);
											users.setIsyear(true);
											break;
										// d.第4类 电话卡
										case 4:
											break;
										// e.第5类 购物余额
										case 5:
											// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
											users.setShopBalance(users.getShopBalance() + cards.getMoney());
											// 变更的购物金额
											changeS = BigDecimal.valueOf(cards.getMoney());
											users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd").format(
													Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate())));
											// 变更后的购物金有效期
											changeTimeS = Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate());
											changeTimeB = beforeTimeB;
											if (cards.getIsupdateshop() == 1){
												if (curusers.getIsupdateshop() == 1){
													users.setShopid(cards.getParentid());
												}
											}
											// 更新用户状态
											subscribersService.updateByPrimaryKeySelective(users);
											// 更改卡状态
											cards.setStatus(1);
											cards.setUsetime(Produce.getNowDate());
											cards.setMobile(mobile);
											rechargeablecardsService.updateByPrimaryKeySelective(cards);

											if (!parentId.equals("68403bea3cae46d9b05650011ce9cab1")){
												payinfoesService.insert(mobile, cards.getCardno(), cards.getPwd(),
														cards.getParentid(), true, cards.getMoney(), true, 1, null, null,
														null, 2);
											}else{
												payinfoesService.insert(mobile, cards.getCardno(), cards.getPwd(),
														users.getShopid(), true, cards.getMoney(), true, 1, null, null,
														null, 2);
											}

											try {
												// 充值变更记录
												changeRecordService.insertSelective(new ChangeRecord(users.getParentid(), users.getShopid(),
														users.getId(), Produce.getNowDate(), beforeB, changeB, 1, beforeTimeB, changeTimeB,
														"卡密充值", beforeS, changeS, 1, beforeTimeS, changeTimeS, "卡密充值", remark));
											} catch (Exception e) {
												logsService.insert(CommContent.TYPE_CREATE, mobile + "卡密充值余额变更记录异常", agent.getUsername(), true,
														IP.getIpAddr(request));
											}

											// 发送短信
											SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
											smsconfigsExample.getOredCriteria().add(smsconfigsExample.createCriteria()
													.andAgentidEqualTo(parentid).andDatastatusEqualTo(true));
											List<Smsconfigs> s = smsconfigsService.selectByExample(smsconfigsExample);
											if (s != null && s.size() > 0) {
												Smsconfigs sms = s.get(0);
												if (sms.getCount() > 0) {
													switch (agent.getSmstype()){
														case 1:
															String jsondata = SmsHelper.SendSms(mobile, money, sms.getMzid(),
																	sms.getSignid(), sms.getType());
															WebHelper.PostData(sms.getUrl(), jsondata, sms.getContenttype(),
																	null);
															break;
														case 3:
															RYSmsHelper.sendRecharge(mobile, agent.getUsername(), money, 2);
															break;
													}
												}
											}
											logsService.insert(CommContent.TYPE_CREATE,
													"成功为" + mobile + "的账号充值" + money + "元", usernamesys, true,
													IP.getIpAddr(request));
											out.print(SUCCESS);
											break;
										}
										if (cards.getType() != 5) {
											String payinfo = VosHelper
													.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
															+ users.getMobile() + "\",\"ownerType\":\"2\",\"money\":\""
															+ cards.getMoney() + "\",\"memo\":\"" + agent.getUsername()
															+ "充值卡(" + pwd + "),充值" + cards.getMoney() + "元\"}");

											VosModelList v1 = GsonUtil.getObject(payinfo, VosModelList.class);
											if (v1.retCode == 0) {
												// 变更话费金额
												changeB = BigDecimal.valueOf(cards.getMoney());
												if (cards.getIsupdateshop() == 1){
													if (curusers.getIsupdateshop() == 1){
														users.setShopid(cards.getParentid());
													}
												}
												// TODO 设置数据库里 账号的有效时间
												users.setEndtime(Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate()));
												// 变更后话费有效期
												changeTimeB = Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate());
												// 变更后购物金有效期
												changeTimeS = beforeTimeS;
												subscribersService.updateByPrimaryKeySelective(users);
												cards.setStatus(1);
												cards.setUsetime(Produce.getNowDate());
												cards.setMobile(users.getMobile());
												rechargeablecardsService.updateByPrimaryKeySelective(cards);
												// TODO 本地更新用户截止日期，判断截止日期进行更新
												String upuserinfo = VosHelper
														.ModifyVosAccount(
																"{\"account\":\"" + agent.getAgentprefix()
																		+ users.getMobile() + "\",\"feeRateGroup\":\""
																		+ cards.getFeelroute()
																		+ "\",\"agentAccount\":\""
																		+ cardAgents.getUsername()
																		+ "\",\"validTime\":\""
																		+ Produce.plusDay(cards.getProbationperiod(),
																				Produce.getNowDate()).getTime()
																		+ "\"}");

												VosModelList v2 = GsonUtil.getObject(upuserinfo, VosModelList.class);
//												if (v2 != null && v2.retCode == 0) {

												// 如果类型为等值卡 送话费等值的购物金
												if(cards.getType() == 6){
													// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
													users.setShopBalance(users.getShopBalance() + cards.getMoney());
													// 变更的购物金额
													changeS = BigDecimal.valueOf(cards.getMoney());
													users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd").format(
															Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate())));
													// 变更后的购物金有效期
													changeTimeS = Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate());
													if (cards.getIsupdateshop() == 1){
														if (curusers.getIsupdateshop() == 1){
															users.setShopid(cards.getParentid());
														}
													}
													// 更新用户状态
													subscribersService.updateByPrimaryKeySelective(users);
													// 更改卡状态
													cards.setStatus(1);
													cards.setUsetime(Produce.getNowDate());
													cards.setMobile(users.getMobile());
													rechargeablecardsService.updateByPrimaryKeySelective(cards);

													if (!parentId.equals("68403bea3cae46d9b05650011ce9cab1")){
														payinfoesService.insert(users.getMobile(), cards.getCardno(), cards.getPwd(),
																cards.getParentid(), true, cards.getMoney(), true, 1, null, null,
																null, 3);
													}else{
														payinfoesService.insert(users.getMobile(), cards.getCardno(), cards.getPwd(),
																users.getShopid(), true, cards.getMoney(), true, 1, null, null,
																null, 3);
													}

												}else if(cards.getType() == 7){
													cards.setStatus(1);
													cards.setUsetime(Produce.getNowDate());
													cards.setMobile(users.getMobile());
													rechargeablecardsService.updateByPrimaryKeySelective(cards);

													RechargeablecardsGift gift = rechargeablecardsGiftService.selectByBatch(cards.getBatch());
													// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
													users.setShopBalance(users.getShopBalance() + gift.getShopmoney());
													// 变更的购物金额
													changeS = BigDecimal.valueOf(cards.getMoney());
													users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd").format(
															Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate())));
													// 变更后的购物金有效期
													changeTimeS = Produce.plusDay(cards.getProbationperiod(), Produce.getNowDate());
													if (cards.getIsupdateshop() == 1){
														if (agent.getIsupdateshop() == 1){
															users.setShopid(cards.getParentid());
														}
													}
													// 更新用户状态
													users.setIsusercard(1);
													subscribersService.updateByPrimaryKeySelective(users);

													rechargeablecardsService.updateByPrimaryKeySelective(cards);

													if (!parentId.equals("68403bea3cae46d9b05650011ce9cab1")){
														payinfoesService.insert(users.getMobile(), cards.getCardno(), cards.getPwd(),
																cards.getParentid(), true, cards.getMoney(), true, 1, null, null,
																null, 4);
													}else{
														payinfoesService.insert(users.getMobile(), cards.getCardno(), cards.getPwd(),
																users.getShopid(), true, cards.getMoney(), true, 1, null, null,
																null, 4);
													}
												}else{
													if (!parentId.equals("68403bea3cae46d9b05650011ce9cab1")){
														payinfoesService.insert(users.getMobile(), cards.getCardno(), cards.getPwd(),
																cards.getParentid(), true, cards.getMoney(), true, 1, null, null, null,
																1);
													}else{
														payinfoesService.insert(users.getMobile(), cards.getCardno(), cards.getPwd(),
																users.getShopid(), true, cards.getMoney(), true, 1, null, null, null,
																1);
													}
												}

												try {
													// 充值变更记录
													changeRecordService.insertSelective(new ChangeRecord(users.getParentid(),
															users.getShopid(), users.getId(), Produce.getNowDate(), beforeB,
															changeB, 1, beforeTimeB, changeTimeB, "卡密充值", beforeS, changeS,
															1, beforeTimeS, changeTimeS, "卡密充值", remark));
												} catch (Exception e) {
													logsService.insert(CommContent.TYPE_CREATE, mobile + "卡密充值余额变更记录异常", agent.getUsername(), true,
															IP.getIpAddr(request));
												}

												// 推送充值信息
//												try{
//													if (agent.getIsrechargepush() == 1){
//														List<JpushId> jpushId = jpushIdService.selectByUserID(users.getId());
//														if (jpushId != null){
//															JPushUtil.setPush("成功充值话费" + changeB + "元,购物金" + changeS + "元", jpushId.get(0).getRegistrationid(), agent);
//														}
//													}
//												}catch (Exception e){
//													System.out.println("推送异常");
//												}

												// 发送短信
												SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
												smsconfigsExample.getOredCriteria()
														.add(smsconfigsExample.createCriteria()
																.andAgentidEqualTo(parentid)
																.andDatastatusEqualTo(true));
												List<Smsconfigs> s = smsconfigsService
														.selectByExample(smsconfigsExample);
												if (s != null && s.size() > 0) {
													Smsconfigs sms = s.get(0);
													if (sms.getCount() > 0) {
														switch (agent.getSmstype()){
															case 1:
																String jsondata = null;
																if (cards.getType() != 4) {
																	jsondata = SmsHelper.SendSms(mobile, mobile,
																			sms.getTcid(), sms.getSignid(), sms.getType());
																} else {
																	jsondata = SmsHelper.SendSms(mobile, money,
																			sms.getMzid(), sms.getSignid(), sms.getType());
																}
																WebHelper.PostData(sms.getUrl(), jsondata,
																		sms.getContenttype(), null);
																break;
															case 3:
																RYSmsHelper.sendRecharge(mobile, agent.getUsername(), money, 2);
																break;
														}
													}
												}
												logsService.insert(CommContent.TYPE_CREATE,
														"成功为" + mobile + "的账号充值" + money + "元", usernamesys, true,
														IP.getIpAddr(request));
												out.print(SUCCESS);
//												} else {
//													logsService.insert(CommContent.TYPE_CREATE,
//															"尝试为" + mobile + "的账号充值" + money + "元，但是失败了", usernamesys,
//															true, IP.getIpAddr(request));
//													out.print("充值失败");
//												}
											}
										}

									} else {
										logsService.insert(CommContent.TYPE_CREATE,
												"尝试为" + mobile + "的账号充值" + money + "元，但是失败了", usernamesys, true,
												IP.getIpAddr(request));
										out.print("充值失败，您的代理商未查到");
									}
								} else {
									logsService.insert(CommContent.TYPE_CREATE,
											"尝试为" + mobile + "的账号充值" + money + "元，但是失败了", usernamesys, true,
											IP.getIpAddr(request));
									out.print("充值失败，您的卡存在权限异常");
								}
							} else {
								logsService.insert(CommContent.TYPE_CREATE,
										"尝试为" + mobile + "的账号充值" + money + "元，但是失败了", usernamesys, true,
										IP.getIpAddr(request));
								out.print("充值失败，您的卡密已经过期");
							}
						} else {
							logsService.insert(CommContent.TYPE_CREATE, "尝试为" + mobile + "的账号充值" + money + "元，但是失败了",
									usernamesys, true, IP.getIpAddr(request));
							out.print("您输入的充值卡有误或已被充值，请检查充值卡号以及密码");
						}
					}
				} else {
					logsService.insert(CommContent.TYPE_CREATE, "尝试为" + mobile + "的账号充值" + money + "元，但是失败了",
							usernamesys, true, IP.getIpAddr(request));
					out.print("请检查该用户是否真实存在,或是否被冻结");
					return;
				}
			}

			break;
		case 2:
			// 2.验证用户是否存在
			String pid = "";
			if(curusers.getAirrecharge() == 0){
				out.print("您不具备此权限");
				return;
			}
			if (curusers.getRole() == 0) {// admin无法充值
				out.print("ADMIN用户无法为用户充值");
				return;
			} else if (curusers.getRole() == 1) {// OEM查询自己的用户充值
				pid = curusers.getId();
			} else if (curusers.getRole() == 2) {// 商家查询OEM下用户充值
				pid = curusers.getParentid();
				//TODO
				if(money != null) {
					if(money != 0) {
						out.print("您无此充值权限");
						return;
					}
				}
				if(shopMoney !=null) {
					if(shopMoney != 0 ) {
						out.print("您无此充值权限");
						return;
					}
				}
			}
			SubscribersExample subscribersExample = new SubscribersExample();
			subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(mobile)
					.andParentidEqualTo(pid).andDatastatusEqualTo(true));
			List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
			Subscribers users = null;
			if (subscribers.size() > 0) {
				users = subscribers.get(0);
			} else {
				logsService.insert(CommContent.TYPE_CREATE, "尝试为" + mobile + "的账号充值" + money + "元，但是失败了", usernamesys,
						true, IP.getIpAddr(request));
				out.print("请检查该用户是否真实存在,或是否被冻结");
				return;
			}
			if (money == null && shopMoney == null) {
				out.print("请填写金额或者购物金额数字！");
				return;
			} else {
				UsersExample usersExample = new UsersExample();
				usersExample.getOredCriteria()
						.add(usersExample.createCriteria().andDatastatusEqualTo(true).andIdEqualTo(parentid));
				List<Users> agents = usersService.selectByExample(usersExample);
				// 3. 验证该用户的代理商是否存在
				if (agents != null && agents.size() == 1) {
					Users agent = agents.get(0);

					// 查询充值者 变更前话费余额
					BigDecimal beforeB = new BigDecimal(0);
					//备注
					String remark = null;
					try {
						// TODO 暂时配注
						String userR = VosHelper
								.GetVosAccount("{accounts:['" + agent.getAgentprefix() + users.getMobile() + "']}");
						if (userR != null) {
							VosModelList userR1 = GsonUtil.getObject(userR, VosModelList.class);
							if (userR1.retCode == 0) {
								beforeB = userR1.infoCustomers[0].getMoney();
							} else {
								beforeB = new BigDecimal(0);
								remark = "暂无记录";
							}
						}
					} catch (Exception e) {
						beforeB = new BigDecimal(0);
						remark = "暂无记录";
					}
					//查询充值者  变更前话费有效期
					Date beforeTimeB = users.getEndtime();
					// 查询充值者  变更前购物金余额
					BigDecimal beforeS = BigDecimal.valueOf(users.getShopBalance());
					// 查询充值者 变更前购物金有效期
					Date beforeTimeS = new SimpleDateFormat("yyyy-MM-dd")
							.parse(users.getShopEnddate());
					// 变更话费金额
					BigDecimal changeB = new BigDecimal(0);
					// 变更购物金额
					BigDecimal changeS = new BigDecimal(0);
					// 查询充值者 变更后话费有效期
					Date changeTimeB = new Date();
					// 查询充值者 变更后购物金有效期
					Date changeTimeS = new Date();

					if (money == null) {
						money = 0;
					}
					if (shopMoney != null) {
						// 充值购物余额，设定有效期，陔余额不可打电话 只可以购物
						if (curusers.getRole() > 1){
							users.setShopid(parentid);
						}
						users.setShopBalance(users.getShopBalance() + shopMoney);
						// 变更购物金额
						changeS = BigDecimal.valueOf(shopMoney);
						// 1.验证参数是否传递
						if (pushDate != null && pushDate != 0) {
							users.setShopEnddate(new SimpleDateFormat("yyyy-MM-dd")
									.format(Produce.plusDay(pushDate, Produce.getNowDate())));
							// 变更后购物金有效期
							changeTimeS = Produce.plusDay(pushDate, Produce.getNowDate());
						}else {
							// 变更后购物金有效期
							changeTimeS = beforeTimeS;
						}
						// 更新用户状态
						subscribersService.updateByPrimaryKeySelective(users);
 						if (!parentId.equals("68403bea3cae46d9b05650011ce9cab1")){
							payinfoesService.insert(mobile, null, null, parentid, true, money, true, 2, null, null, null,
									0);
						}else{
							payinfoesService.insert(mobile, null, null, users.getShopid(), true, money, true, 2, null, null, null,
									0);
						}

//						// 发送短信
//						SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
//						smsconfigsExample.getOredCriteria().add(smsconfigsExample.createCriteria()
//								.andAgentidEqualTo(parentid).andDatastatusEqualTo(true));
//						List<Smsconfigs> s = smsconfigsService.selectByExample(smsconfigsExample);
//						if (s != null && s.size() > 0) {
//							Smsconfigs sms = s.get(0);
//							if (sms.getCount() > 0) {
//								String jsondata = SmsHelper.SendSms(mobile, shopMoney, sms.getMzid(), sms.getSignid(),
//										sms.getType());
//								WebHelper.PostData(sms.getUrl(), jsondata, sms.getContenttype(), null);
//							}
//						}
						logsService.insert(CommContent.TYPE_CREATE, "成功为" + mobile + "的账号充值" + money + "元", usernamesys,
								true, IP.getIpAddr(request));
						out.print(SUCCESS);
					}

					String payinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
							+ users.getMobile() + "\",\"ownerType\":\"2\",\"money\":\"" + money + "\",\"memo\":\""
							+ agent.getUsername() + "，空中充值" + money + "元\"}");

					VosModelList v1 = GsonUtil.getObject(payinfo, VosModelList.class);
					if (v1.retCode == 0) {
						// 变更话费金额
						changeB = BigDecimal.valueOf(money);
						String upuserinfo = null;
						if (pushDate != null && pushDate != 0) {
							System.out.println("空中充值变更有效期:"+pushDate);
							// TODO 本地更新用户截止日期，判断截止日期进行更新
							upuserinfo = VosHelper.ModifyVosAccount("{\"account\":\"" + agent.getAgentprefix()
									+ users.getMobile() + "\",\"feeRateGroup\":\"" + agent.getFreeroute()
									+ "\",\"agentAccount\":\"" + agent.getUsername() + "\",\"validTime\":\""
									+ Produce.plusDay(pushDate, Produce.getNowDate()).getTime() + "\"}");
							System.out.println("空中充值变更后:"+upuserinfo);
						} else {
							upuserinfo = VosHelper.ModifyVosAccount("{\"account\":\"" + agent.getAgentprefix()
									+ users.getMobile() + "\",\"feeRateGroup\":\"" + agent.getFreeroute()
									+ "\",\"agentAccount\":\"" + agent.getUsername() + "\"}");
						}
						VosModelList v2 = GsonUtil.getObject(upuserinfo, VosModelList.class);
						if (v2 != null && v2.retCode == 0) {
							// 变更后购物金有效期
							changeTimeB = Produce.plusDay(pushDate, Produce.getNowDate());
							if (!parentId.equals("68403bea3cae46d9b05650011ce9cab1")){
								payinfoesService.insert(mobile, null, null, parentid, true, money, true, 2, null, null,
										null, 0);
							}else{
								payinfoesService.insert(mobile, null, null, users.getShopid(), true, money, true, 2, null, null,
										null, 0);
							}

							if (money != 0) {
								// 推送充值信息
//								try{
//									if (agent.getIsrechargepush() == 1){
//										List<JpushId> jpushId = jpushIdService.selectByUserID(users.getId());
//										if (jpushId != null && jpushId.size() > 0){
//											JPushUtil.setPush("成功充值话费" + changeB + "元,购物金" + changeS + "元", jpushId.get(0).getRegistrationid(), agent);
//										}
//									}
//								}catch (Exception e){
//									System.out.println("推送异常");
//								}

								// 发送短信
								SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
								smsconfigsExample.getOredCriteria().add(smsconfigsExample.createCriteria()
										.andAgentidEqualTo(parentid).andDatastatusEqualTo(true));
								List<Smsconfigs> s = smsconfigsService.selectByExample(smsconfigsExample);
								if (s != null && s.size() > 0) {
									Smsconfigs sms = s.get(0);
									if (sms.getCount() > 0) {
										switch (agent.getSmstype()){
											case 1:
												String jsondata = null;
												jsondata = SmsHelper.SendSms(mobile, money, sms.getMzid(), sms.getSignid(),
														sms.getType());
												WebHelper.PostData(sms.getUrl(), jsondata, sms.getContenttype(), null);
												break;
											case 3:
												RYSmsHelper.sendRecharge(mobile, agent.getUsername(), money, 1);
												break;
										}
									}
								}

								try {
									Users sUser = usersService.selectByPrimaryKey(users.getShopid());
									if (sUser.getBalance().compareTo(new BigDecimal(money)) == 1){
										sUser.setBalance(sUser.getBalance().subtract(new BigDecimal(money)));
										usersService.updateByPrimaryKeySelective(sUser);
									}else{
										Users pUser = usersService.selectByPrimaryKey(users.getParentid());
										pUser.setBalance(pUser.getBalance().subtract(new BigDecimal(money)));
										usersService.updateByPrimaryKeySelective(pUser);
									}
								}catch (Exception e){
									System.out.println("费用扣除失败");
								}
							}

							users.setShopid(parentid);

							try {
								// 充值变更记录
								changeRecordService.insertSelective(new ChangeRecord(users.getParentid(), users.getShopid(),
										users.getId(), Produce.getNowDate(), beforeB, changeB, 1, beforeTimeB, changeTimeB,
										"空中充值", beforeS, changeS, 1, beforeTimeS, changeTimeS, "空中充值", remark));
							} catch (Exception e) {
								logsService.insert(CommContent.TYPE_CREATE, mobile + "空中充值余额变更记录异常", agent.getUsername(), true,
										IP.getIpAddr(request));
							}

							// 更新用户状态
							subscribersService.updateByPrimaryKeySelective(users);
							logsService.insert(CommContent.TYPE_CREATE, "成功为" + mobile + "的账号充值" + money + "元",
									usernamesys, true, IP.getIpAddr(request));
							out.print(SUCCESS);
						} else {
							logsService.insert(CommContent.TYPE_CREATE, "尝试为" + mobile + "的账号充值" + money + "元，但是失败了",
									usernamesys, true, IP.getIpAddr(request));
							out.print("充值失败");
						}
					} else {
						logsService.insert(CommContent.TYPE_CREATE, "尝试为" + mobile + "的账号充值" + money + "元，但是失败了",
								usernamesys, true, IP.getIpAddr(request));
						out.print("充值失败");
					}
				} else {
					logsService.insert(CommContent.TYPE_CREATE, "尝试为" + mobile + "的账号充值" + money + "元，但是失败了",
							usernamesys, true, IP.getIpAddr(request));
					out.print("充值失败，您的代理商未查到");
				}
				break;
			}
		}
	}
}
